package model;

import util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDAO {

//    根据用户名 获取用户信息 用于登录
    public User getUserByName(String name){
        User user = null;
        try (Connection connection = DBUtil.getConnection()) {
            String sql = "select * from users where name = ?";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1, name);
                try (ResultSet resultSet = statement.executeQuery()) {
                    while (resultSet.next()) {
                        user = new User();
                        user.setId(resultSet.getInt("id"));
                        user.setName(resultSet.getString("name"));
                        user.setPassword(resultSet.getString("password"));
                        user.setGroup_id(resultSet.getInt("group_id"));
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }


//    用户注册
    public boolean addUser(User user) {
        try (Connection connection = DBUtil.getConnection()) {
//            因为 id 为自增主键 所以不需要操作
            String sql = "insert into users (name, password, group_id) values (?, ?, ?)";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1, user.getName());
                statement.setString(2, user.getPassword());
                statement.setInt(3, user.getGroup_id());

                // 执行插入操作，并返回受影响的行数
                int rowsInserted = statement.executeUpdate();
                // 检查是否成功插入预期的行数（此处为1，因为每次只插入一个用户）
                return rowsInserted == 1;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }

//    修改用户信息
    public boolean updateUser(User user){
        boolean success = false;
        try(Connection connection = DBUtil.getConnection()){
            String sql = "update users set name = ? ,password = ?, group_id = ? where id = ?";//更新用户信息
            try(PreparedStatement statement = connection.prepareStatement(sql)){
                statement.setString(1,user.getName());
                statement.setString(2,user.getPassword());
                statement.setInt(3,user.getGroup_id());
                statement.setInt(4,user.getId());

                int rowsUpdated = statement.executeUpdate();
                success = rowsUpdated > 0;
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
        return success;
    }

}
